package org.tony.nio.demo.channels;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 
 * @author tony
 * 
 */
public class ChannelAccept
{

	public static void main(String[] args) throws IOException
	{
		int port = 9999;
		ByteBuffer bf = ByteBuffer.wrap("Hello world".getBytes());
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ServerSocket socket = ssc.socket();
		socket.bind(new InetSocketAddress(port));
		ssc.configureBlocking(false);
		while (true)
		{
			System.out.println("Waiting for connection ...");
			SocketChannel sc = ssc.accept();
			if (sc == null)
			{
				try
				{
					Thread.sleep(2000);
				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
			else
			{
				System.out.println("Imcoing connection from:" + sc.socket().getLocalAddress());
				bf.rewind();
				sc.write(bf);
				sc.close();
			}
		}

	}

}
